package com.gzp.transaction;

import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * 队列的消费者事务。
 * 
 * @author Administrator
 *
 */
public class TestQueueConsumer {

	private static final String brokerURL = "tcp://localhost:61616";// 在activemq/conf/activemq.xml中
	private static final String queueName = "queue-hello";

	public static void main(String[] args) throws Exception {
		ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL);
		Connection connection = factory.createConnection();
		connection.start();
		/**
		 * 修改签收方式为手动签收，必须要手动签收acknowledge()才能消费消息。
		 */
		Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
		Queue queue = session.createQueue(queueName);
		MessageConsumer messageConsumer = session.createConsumer(queue);
		System.out.println("3号消费者");
		messageConsumer.setMessageListener(new MessageListener() {

			@Override
			public void onMessage(Message message) {
				if (message instanceof TextMessage) {
					TextMessage textMessage = (TextMessage) message;
					try {
						// 手动签收
						textMessage.acknowledge();
						System.out.println("接收到消息，消息内容为：" + textMessage.getText());
					} catch (JMSException e) {
						e.printStackTrace();
					}
				}
			}
		});
		System.in.read();// 不让程序结束
		// 8、关闭资源。
		messageConsumer.close();
		session.close();
		connection.close();
	}
}
